﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZX.Web.UI.Controls;
using ZX.BLL.Extend;
using ZX.Common;
using ZX.BLL;
using ZX.DBModule;
using System.Text;
using System.Data;

using ZX.EHR.Library;
using System.Collections;
using ZX.DAL.DBExtend;
using System.Data.SqlClient;
using ZX.BLL.EHR.Time;
using ZX.Common;

namespace ZX.Web.UI.Controls
{
    public partial class DataAction : BasePage 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string action = this.GetStringFromQueryString("action", "");
            string entity = this.GetStringFromQueryString("entity", "");
            switch (entity)
            {
                #region 部门的相关操作
                case "dept":
                    switch (action.ToLower())
                    {
                        case "move":
                            Move();
                            break;
                        case "movedept":
                            MoveDept();
                            break;
                        case "copydept":
                            CopyDept();
                            break;
                        case "createdeptpath":
                            CreateDeptPath();
                            break;
                        case "rename":
                            DeptRename();
                            break;
                        default:
                            //GetData();
                            break;
                    }
                    break;
                #endregion
                #region 岗位相关操作
                case "post":
                    switch (action.ToLower())
                    {
                        case "stop":
                            StopPost();
                            break;
                        case "setmanagerpost":
                            SetPostManageStatus();
                            break;
                        case "rename":
                            PostRename();
                            break;
                        case "batchadd":
                            AddPost();
                            break;
                        case "copypost":
                            CopyPost();
                            break;
                        case "lowerest": // 最低工资标准
                            SetLowerest();
                            break;

                        default:
                            // GetData();
                            break;
                    }
                    break;
                #endregion
                #region 权限的相关操作
                case "right":
                    switch (action.ToLower())
                    {
                        case "userroles":
                            SetUserRoles();
                            break;
                        case "roleuses":
                            SetRoleUsers();
                            break;
                        case "roleposts":
                            SetRolePosts();
                            break;
                        case  "postroles":
                            SetPostRoles();
                            break;
                        default:
                            break;
                    }
                    break;
                #endregion
                #region  人员异动操作
                case "employee":
                    switch (action.ToLower())
                    {
                        case "leave"://离职
                            break;
                        case "movepost"://转岗
                            break;
                        case "back"://返聘
                            break;
                        case "live"://转正
                            break;
                        case "audit"://审核
                            SetAudit();
                            break;
                        default:
                            break;
                    }
                    break;
                #endregion
                #region 薪资相关
                case "salary":
                    switch (action.ToLower())
                    {
                        case "addrole":
                            AddRoleField();
                            break;
                    }
                    break;
                #endregion
                #region 考勤
                case "time":
                    switch (action)
                    {
                        case "caleavetime":
                            string empID = GetStringFromQueryString("empid", Guid.Empty.ToString());
                            string bTime = GetStringFromQueryString("btime", DateTime.Now.ToString());
                            string eTime = GetStringFromQueryString("etime", DateTime.Now.ToString());
                            int isInclud = this.GetIntFromQueryString("includ",0);
                            GetCalLeave(empID, bTime, eTime, isInclud);
                            break;

                    }
                    break;
                case "initPassword":
                    InitPassword();
                    break;
                #endregion
                default:
                    switch (action)
                    {
                            case "runProc":
                            if (entity == "proc")
                            {
                                string procName = this.GetStringFromQueryString("procName", "");
                                string parameters = this.GetStringFromQueryString("parameters", "");
                                RunPrc(procName, parameters);
                            }
                            if (entity == "proc2")
                            {
                                string procName = this.GetStringFromQueryString("procName", "");
                                string parameters = this.GetStringFromQueryString("parameters", "");
                                RunPrc2(procName, parameters);
                            }
                            break;
                        default:
                            break;
                    }
                    break;

            }         
            
        }
        #region 考勤
        void GetCalLeave(string employeeID,string bTime,string eTime,int isIncludHoliday)
        {
            float day = 0.0f;
            string msg = "";
            Ehr_Scheduling obj = new Ehr_Scheduling();
            float time = obj.HRGetEmpTotalVation(new Guid(employeeID), Convert.ToDateTime(bTime), Convert.ToDateTime(eTime),isIncludHoliday, out day, out msg);
            this.Response.Write("{" + string.Format("'day':'{0}','time':'{1}'", day, time) + "}");
            this.Response.End();
        }
        #endregion

        #region 权限相关操作
        /// <summary>
        /// 设置用户角色
        /// </summary>
        void SetUserRoles()
        {
            string[] roles = this.GetStringFromQueryString("roles", "").Split(',');
            Guid? userID = GetGuidFromQueryString("userid");
            foreach (var roleid in roles)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysUserRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["UserID"] = userID;
                entity.DRow["RoleID"] = new Guid(roleid);
                entity.DRow["Remark"] = "";
                entity.TableKey = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }
        /// <summary>
        /// 设置角色用户
        /// </summary>
        void SetRoleUsers()
        {
            string[] users = this.GetStringFromQueryString("users", "").Split(',');
            Guid? roleid = GetGuidFromQueryString("roleid");
            foreach (var userid in users)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysUserRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["UserID"] = new Guid(userid);;
                entity.DRow["RoleID"] = roleid;
                entity.DRow["Remark"] = "";
                entity.TableKey = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }
        /// <summary>
        /// 设置角色岗位
        /// </summary>
        void SetRolePosts()
        {
            string[] posts = this.GetStringFromQueryString("posts", "").Split(',');
            Guid? roleid = GetGuidFromQueryString("roleid");
            foreach (var postid in posts)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysPostRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["RoleID"] = roleid;
                entity.DRow["PostID"] = new Guid(postid);
                entity.DRow["Remark"] = "";
                entity.TableKey = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }
        /// <summary>
        /// 设置岗位角色
        /// </summary>
        void SetPostRoles()
        {
            string[] roles = this.GetStringFromQueryString("roles", "").Split(',');
            Guid? postid = GetGuidFromQueryString("postid");
            foreach (var roleid in roles)
            {
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "SysPostRole";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["PostID"] = postid;
                entity.DRow["RoleID"] = new Guid(roleid);
                entity.DRow["Remark"] = "";
                entity.TableKey = entity.GetKey()[0];
                this._bll.entity = entity;
                try
                {
                    this._bll.Insert(entity);
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }
        #endregion

        #region 部门相关操作
        /// <summary>
        /// 部门重命名
        /// </summary>
        void DeptRename()
        {
            BDept bdept = new BDept();
            DatDepartment _dept = bdept.GetEntityById<DatDepartment>(GetGuidFromQueryString("deptID"));
            _dept.DeptName = GetStringFromQueryString("newDeptName", "");
            bdept.entity = _dept;
            if (bdept.Update())
            {
                Response.Write("1");
            }
            Response.Write("0");
        }


        /// <summary>
        /// 部门移动
        /// </summary>
        void MoveDept()
        {
            BDept dept = new BDept();
            if (dept.DeptMove(GetGuidFromQueryString("sourceID"), GetGuidFromQueryString("parentID")))
            {
                Response.Write("1");
            }
        }

        /// <summary>
        /// 拷贝部门
        /// </summary>
        void CopyDept()
        {
            BDept dept = new BDept();
            if (dept.DeptCopy(GetGuidFromQueryString("sourceID")))
            {
                Response.Write("1");
            }

        }


       
        /// <summary>
        /// 移动
        /// </summary>
        private void Move()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            switch (strEntity.ToLower())
            {
                case "datdepartment":
                    //取消用户区域权限设置
                    moveDepartment();
                    break;
            }
        }
        
        /// <summary>
        /// 移动组织架构
        /// </summary>
        private void moveDepartment()
        {
            BaseBussnies bll = new BaseBussnies();
            //需要移动的部门ID集合
            string[] deptIds = ZXContext.Request.Form["jsonDataContent"].ToString().Split(',');
            //移动到部门
            string parentId = this.GetStringFromQueryString("parentId", "");
            string sql = "Exec sp_MoveDepartment '{0}','{1}'";
            sql = string.Format(sql, deptIds, parentId);
            try
            {
                bll.RunSqlCommand(sql);
                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }

        }

        /// <summary>
        /// 生成部门树
        /// </summary>
        private void CreateDeptPath()
        {
            ZX.BLL.BDept bll = new ZX.BLL.BDept();
            Guid parentId = new Guid(Request.QueryString["parentId"]);
            HttpContext.Current.Response.Write(bll.CreateNewTreeCode(parentId));
        }
        
        /// <summary>
        /// 部门人员信息
        /// </summary>
        private void GetDeptUser()
        {
            //try
            //{
            //    string deptId = this.GetStringFromQueryString("deptId", "");
            //    BaseBussnies bll = new BaseBussnies();
            //    IList<V_UserEmp> _list = bll.GetEntitys<V_UserEmp>("DeptID='" + deptId + "'");
            //    if (_list != null && _list.Count > 0)
            //    {
            //        StringBuilder sb = new StringBuilder();
            //        foreach (V_UserEmp userEmp in _list)
            //        {
            //            sb.Append(userEmp.UserID.ToString());
            //            sb.Append(",");
            //            sb.Append(userEmp.Name + " [" + userEmp.DeptName + "]");
            //            sb.Append("~");
            //        }
            //        HttpContext.Current.Response.Write(sb.ToString());
            //    }
            //    else
            //    {
            //        HttpContext.Current.Response.Write("0");
            //    }
            //}
            //catch
            //{
            //    HttpContext.Current.Response.Write("0");
            //}
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private void GetDeptUsers()
        {
            //try
            //{
            //    string deptId = this.GetStringFromQueryString("deptId", "");
            //    BaseBussnies bll = new BaseBussnies();
            //    IList<V_UserEmp> _list = bll.GetEntitys<V_UserEmp>("DeptID='" + deptId + "'");
            //    if (_list != null && _list.Count > 0)
            //    {
            //        StringBuilder sb = new StringBuilder();
            //        foreach (V_UserEmp userEmp in _list)
            //        {
            //            sb.Append(userEmp.UserID.ToString());
            //            sb.Append(",");
            //            sb.Append(userEmp.Name + " [" + userEmp.DeptName + "]");
            //            sb.Append("~");
            //        }
            //        HttpContext.Current.Response.Write(sb.ToString());
            //    }
            //    else
            //    {
            //        HttpContext.Current.Response.Write("0");
            //    }
            //}
            //catch
            //{
            //    HttpContext.Current.Response.Write("0");
            //}
        }


        /// <summary>
        /// 
        /// </summary>
        private void GetDeptEmployees()
        {

        }

        #endregion

        #region 岗位相关操作

        /// <summary>
        /// 停用标识
        /// </summary>
        void StopPost()
        {

        }

        void SetLowerest()
        {
            string[] _posts = this.GetStringFromQueryString("posts", "").Split(',');
            Guid? cityID =GetGuidFromQueryString("CityLowerestSalaryID");
            foreach (var postid in _posts)
            { 
                DataTableBaseEntity entity = new DataTableBaseEntity();
                entity.TableName = "salPostCityLowerestSalary";
                entity.CreateDT();
                entity.DRow[entity.getKey()] = Guid.NewGuid();
                entity.DRow["CityLowerestSalaryID"] = cityID;
                entity.DRow["PostID"] = new Guid(postid);
                entity.DRow["Notes"] ="";
                entity.TableKey = entity.GetKey()[0];
                this._bll.entity = entity;

                try
                {
                    this._bll.Insert(entity);
                }
                catch(Exception e)
                {
                    HttpContext.Current.Response.Write(e.Message);
                }
                //entity.EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                //HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
            }
            HttpContext.Current.Response.Write("1");
        }
        //设置主管标识
        void SetPostManageStatus()
        {
            ZX.BLL.EHR.BDatPost bPost = new BLL.EHR.BDatPost();
            bPost.SetManagerPost(GetGuidFromQueryString("postid"));
            Response.Write("1");
        }

        //岗位名称更改
        void PostRename()
        {

        }

        //新增岗位
        void AddPost()
        {
            IList<DatPost> list = ZX.Common.Globals.JSonToObject<IList<DatPost>>(GetStringFromQueryString("json", ""));
            ZX.BLL.EHR.BDatPost bPost = new BLL.EHR.BDatPost();
            foreach (var e in list)
            {
                e.AddUser = this.User.UserID;
            }
            bPost.BatchAddPost(list);
            Response.Write("1");
            //DatPost post = new DatPost();
        }

        //岗位复制
        void CopyPost()
        {
            string sourceDeptID = GetStringFromQueryString("sourceDeptID", "");
            Guid targetDeptID = GetGuidFromQueryString("targetDeptID");
            
            ZX.BLL.EHR.BDatPost bPost = new BLL.EHR.BDatPost();
            IList<DatPost> list = bPost.GetEntitys<DatPost>("DeptID='" + sourceDeptID + "'");
            if (list == null)
            {
                Response.Write("0");
                return;
            }
            foreach (var e in list)
            {
                e.AddUser = this.User.UserID;
                e.DeptID = targetDeptID;
            }
            bPost.BatchAddPost(list);
            Response.Write("1");
        }



        #endregion

        #region 人员相关操作

        /// <summary>
        /// 人员审核
        /// </summary>
        void SetAudit()
        {
            string empID = GetStringFromQueryString("id", "");
            int i = this._bll.RunSqlCommand(string.Format("update hremployee set EmployeeStatus='{0}',Auditor='{1}',Audittime='{3}' where ID='{2}'", 1, this.UserId, empID, System.DateTime.Now));
            if (i > 0)
            {
                Response.Write("1");

            }
            else
            {
                Response.Write("0");
            }
            Response.End();
        } 
        #endregion 

        #region 薪资相关
        void AddRoleField()
        {
            DataTable dt = this._bll.GetDataBySqlComm("select * from CrmCommisionRole order by AddTime");
            Int32 i = 0;
            foreach (DataRow row in dt.Rows)
            {
                i = i + 1;
                AddField(row["ID"],i);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="i"></param>
        void AddField(object roleid,Int32 i)
        {
            DataTable dt = this._bll.GetDataBySqlComm("select * from salSalaryProvisionRoleField where RoleID='"+roleid+"'");
            if (dt.Rows.Count > 0)
            {
                return;
            }
            DataTableBaseEntity entity = new DataTableBaseEntity();
            entity.TableName = "salSalaryProvisionRoleField";
            string[] strKeyArrary = entity.GetKey();
            if (strKeyArrary != null)
            {
                entity.TableKey = strKeyArrary[0];
                entity.KeyType = strKeyArrary[1];
            }
            entity.CreateDT();
            entity.SetValue("ID",Guid.NewGuid());
            entity.SetValue("RoleID",roleid);
            entity.SetValue("Sort",i);
            entity.SetValue("FieldName","Role_" + i.ToString());
            entity.EntityJson ="{"+ string.Format(@"""ID"":""{0}"",""RoleID"":""{1}"",""Sort"":""{2}"",""FieldName"":""{3}""", entity["ID"].ToString(), entity["RoleID"].ToString(), entity["Sort"].ToString(), entity["FieldName"].ToString())+"}";
            entity.FieldValue = ZX.Common.Globals.ConvertToDictionary(entity.EntityJson);
            this._bll.entity = entity;
            this._bll.Insert();
            BLL.Extend.DBTable dbTable = SqlDBTable.Instance;
            dbTable.AddCol("salProvisionCorssData", "Role_" + i.ToString(), "decimal(9,4)");
        }
        #endregion

        /// <summary>
        /// 密码初始化
        /// </summary>
        void InitPassword()
        {
            BaseBussnies bll = new BaseBussnies(new hrEmployee());
            IList<hrEmployee> elist = bll.GetEntitys<hrEmployee>();
            IList<DatUser> ulist = bll.GetEntitys<DatUser>();
            foreach(DatUser user in ulist)
            {
                try
                {
                    if (user.LoginName.ToLower() == "admin")
                        continue;
                    user.Password = elist.Where(p => p.ID == user.EmpID).First().IDCardNO.Substring(12).GetMd5Hash();
                    bll.entity = user;
                    bll.Update();
                }catch(Exception e){}
            }
        }
        #region 执行存储过程
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Sql"></param>
        /// <returns></returns>
        int RunSql(string Sql)
        {
            return this._bll.RunSqlCommand(Sql);
        }

        void RunPrc(string procName, string parameters)
        {
            object[] para = parameters.Split(',');
            try
            {
                var result = this._bll.RunProcedure(procName, para);
                //_bll.GetDataBySqlComm("exec spName '',''");
                //result.Rows
                // result.GetRow(0)
                //if(result.
                var returnValue = "";
                if (result.Rows > 0)
                {
                    returnValue = result.GetRow(0)[0].ToString();
                }
                if (result.Rows == 0)
                {
                    Response.Write("{stuats:1,msg:'" + result.Rows.ToString() + "'}");
                }
                else
                {
                    Response.Write("{stuats:1,msg:'" + result.Rows.ToString() + "',returnValue:'" + returnValue + "'}");
                }

            }
            catch (Exception exp)
            {
                Response.Write("{stuats:0,msg:'" + exp.Message + "'}");

            }
        }

        /// <summary>
        /// 执行存储过程，并返回结果集
        /// </summary>
        /// <param name="procName"></param>
        /// <param name="parameters"></param>
        void RunPrc2(string procName, string parameters)
        {
            object[] para = parameters.Split(',');
            try
            {
                string _para = string.Empty;
                foreach (object p in para)
                {
                    if (_para.Length == 0)
                    {
                        _para = _para + "'" + p.ToString() + "'";
                    }
                    else
                    {
                        _para = _para + ",'" + p.ToString() + "'";
                    }
                }
                DataTable result = _bll.GetDataBySqlComm(string.Format("exec {0} {1}", procName, _para));
                string resultJson = ZX.Common.Globals.DataTableToJSON(result);
                Response.Write(resultJson);
            }
            catch (Exception exp)
            {
                Response.Write("{stuats:0,msg:'" + exp.Message + "'}");
            }
        }
        #endregion

    }

    class Post
    {
        public Guid DutyID
        {
            get;
            set;
        }

        public Guid DeptID
        { 
            get;
            set;
        }
    }
}